import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
// 请求拦截器
service.interceptors.request.use(function(config) {
  // 4.设置请求拦截器,添加请求头
  store.state.user.token && (config.headers['Authorization'] = `Bearer ${store.state.user.token}`)
  return config
}, function(error) {
  return Promise.reject(error)
})
// 请求响应器
service.interceptors.response.use(function(response) {
  // 对响应数据做点什么
  // 7.经过响应拦截器的处理
  if (response.data.success) {
    return response.data
  } else {
    console.log('response', response)
    return response
    // throw new Error(response)
  }
}, async function(error) {
  if (error.response.data.code === 10002) {
    await store.dispatch('user/logout')
    router.push('/login' + encodeURIComponent(router.currentRoute.fullPath))
  }
  return Promise.reject(error)
})

export default service
